package com.pactera.integral.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.pactera.integral.common.repository.QueryResult;
import com.pactera.integral.common.repository.ResultMap;
import com.pactera.integral.dao.UserAdditionalScoreDao;
import com.pactera.integral.dao.UserDao;
import com.pactera.integral.entity.User;
import com.pactera.integral.entity.UserAdditionalScore;
import com.pactera.integral.service.UserAdditonalScoreService;
import com.pactera.integral.util.DateUtil;
import com.pactera.integral.util.SumScore;

@Service
public class UserAdditonalScoreServiceImpl implements UserAdditonalScoreService {

	@Autowired
	private UserAdditionalScoreDao userAdditionalScoreDao;
	@Autowired
	private UserDao userDao;

	// 退回
	private static final int STATUS_REJECT = 0;
	// 新建提交
	private static final int STATUS_NEW = 1;
	// 组长同意
	private static final int STATUS_PASS = 2;
	// 终审通过
	private static final int STATUS_FINAL = 3;

	/**
	 * 积分申请、审核功能
	 * 
	 * @param userAdditionalScore
	 */
	@Override
	public Boolean addScore(String staffId, UserAdditionalScore userAdditionalScore) {
		User user = userDao.findByStaffId(staffId);
		String userId = user.getUserId();
		userAdditionalScore.setUserId(userId);
		if (STATUS_NEW == userAdditionalScore.getStatus()) {
			userAdditionalScore.settLScore(0);
			userAdditionalScore.setAuditScore(0);
			userAdditionalScoreDao.save(userAdditionalScore);
		} else {
			String id = userAdditionalScore.getId();
			UserAdditionalScore existingScore = userAdditionalScoreDao.findById(id);
			if (existingScore != null) {
				if (STATUS_PASS == userAdditionalScore.getStatus()) {
					existingScore.setStatus(STATUS_PASS);
					existingScore.setSuggestion(userAdditionalScore.getSuggestion());
					existingScore.settLScore(userAdditionalScore.gettLScore());
					userAdditionalScoreDao.save(existingScore);
				} else if (STATUS_REJECT == userAdditionalScore.getStatus()) {
					existingScore.setStatus(STATUS_REJECT);
					existingScore.setSuggestion(userAdditionalScore.getSuggestion());
					existingScore.settLScore(0);
					userAdditionalScoreDao.save(existingScore);
				} else if (STATUS_FINAL == userAdditionalScore.getStatus()) {
					String scoreStaffId = userDao.findByUserId(existingScore.getUserId()).getStaffId();
					existingScore.setStatus(STATUS_FINAL);
					existingScore.setAuditScore(userAdditionalScore.getAuditScore());
					userAdditionalScoreDao.save(existingScore);
					SumScore.sum(scoreStaffId, existingScore.getYear(), existingScore.getMonth());
				}
			}
		}
		return Boolean.TRUE;
	}

	/**
	 * 获取申请积分列表
	 * 
	 * @param departmentCode
	 * @return
	 */
	public List<ResultMap<String, Object>> getAdditionalScoreList(String status, String userId) {
		String sqlKey = "additionScoreList.searchByUserId";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("userId", userId);
		parameterMap.put("status", status);
		QueryResult<ResultMap<String, Object>> result = userAdditionalScoreDao.findMapListBySQLKey(sqlKey, parameterMap,
				null);
		return result.getContent();
	}

	public List<ResultMap<String, Object>> getAdditionalScoreDetail(String scoreId) {
		String sqlKey = "additionScoreDetail.searchByScoreId";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("scoreId", scoreId);
		QueryResult<ResultMap<String, Object>> result = userAdditionalScoreDao.findMapListBySQLKey(sqlKey, parameterMap,
				null);
		return result.getContent();
	}

	/**
	 * 根据staffId 获取TeamMember
	 * 
	 * @param departmentCode
	 */
	public List<ResultMap<String, Object>> getUserId(String status, String staffId) {
		String sqlKey = "memberAndScore.searchByDepartmentCode";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		String departmentCode = getDepartmentCodebyStaffId(staffId);
		parameterMap.put("departmentCode", departmentCode);
		parameterMap.put("groupName", "Team Member");
		parameterMap.put("status", status);
		QueryResult<ResultMap<String, Object>> result = userAdditionalScoreDao.findMapListBySQLKey(sqlKey, parameterMap,
				null);

		return result.getContent();
	}

	/**
	 * 查询历史记录
	 * 
	 * @param staffId
	 * @return
	 */
	public List<ResultMap<String, Object>> getApplyHistory(String staffId, String year, String month) {
		String sqlKey = "applyHistory.searchByStaffId";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("staffId", staffId);
		parameterMap.put("year", Integer.valueOf(year));
		parameterMap.put("month", Integer.valueOf(month));
		QueryResult<ResultMap<String, Object>> result = userAdditionalScoreDao.findMapListBySQLKey(sqlKey, parameterMap,
				null);

		return result.getContent();
	}

	/**
	 * 查看用户终审积分列表
	 * 
	 * @param paramMap
	 * @param page
	 * @return
	 */
	@Override
	public QueryResult<ResultMap<String, Object>> searchAdditionalScore(Map<String, Object> paramMap, Pageable page) {

		if (paramMap != null) {
			String quarter = (String) paramMap.get("quarter");
			String year = (String) paramMap.get("year");
			if ("".equals(quarter)) {
				String[] date = DateUtil.getThisQuarter();
				String start = date[0];
				String end = date[1];
				paramMap.put("start", start);
				paramMap.put("end", end);
			} else {
				String[] date = quarter.split(",");
				String start = date[0];
				String end = date[1];
				paramMap.put("start", start);
				paramMap.put("end", end);
			}

			if ("".equals(year)) {
				paramMap.put("year", DateUtil.getThisYear());
			} else {
				paramMap.put("year", year.substring(0, 4));
			}
		}

		return userAdditionalScoreDao.findMapListBySQLKey("userAdditionalScore.searchAdditionalScore", paramMap, page);
	}

	/**
	 * 用户积分终审明细列表
	 * 
	 * @param paramMap
	 * @param pageable
	 * @return
	 */
	@Override
	public QueryResult<ResultMap<String, Object>> searchAdditionalScoreDetailed(Map<String, Object> paramMap,
			Pageable pageable) {

		if (paramMap != null) {
			String quarter = (String) paramMap.get("quarter");
			String year = (String) paramMap.get("year");
			if ("".equals(quarter)) {
				String[] date = DateUtil.getThisQuarter();
				String start = date[0];
				String end = date[1];
				paramMap.put("start", start);
				paramMap.put("end", end);
			} else {
				String[] date = quarter.split(",");
				String start = date[0];
				String end = date[1];
				paramMap.put("start", start);
				paramMap.put("end", end);
			}

			if ("".equals(year)) {
				paramMap.put("year", DateUtil.getThisYear());
			} else {
				paramMap.put("year", year.substring(0, 4));
			}
		}

		return userAdditionalScoreDao.findMapListBySQLKey("userAdditionalScore.searchAdditionalScoreDetailed", paramMap,
				pageable);
	}

	/**
	 * 修改终审积分
	 * 
	 * @param userAdditionalScore
	 * @return
	 */
	@Override
	public Boolean updateAuditScore(UserAdditionalScore userAdditionalScore) {

		UserAdditionalScore existingEntity = userAdditionalScoreDao.findById(userAdditionalScore.getId());
		existingEntity.setAuditScore(userAdditionalScore.getAuditScore());
		existingEntity.setStatus(3);
		userAdditionalScoreDao.save(existingEntity);

		return Boolean.TRUE;
	}

	/**
	 * 查看终审积分明细
	 * 
	 * @param paramMap
	 * @param pageable
	 * @return
	 */
	@Override
	public QueryResult<ResultMap<String, Object>> searchAuditScoreDetailed(Map<String, Object> paramMap,
			Pageable pageable) {

		return userAdditionalScoreDao.findMapListBySQLKey("userAdditionalScore.searchAuditScoreDetailed", paramMap,
				pageable);
	}

	/**
	 * 获取所有额外分项的信息
	 * 
	 * @param scoreType
	 */
	public List<ResultMap<String, Object>> getAllScoreList(String scoreType, String category) {
		String sqlKey = "additionalScore.searchByScoreType";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("scoreType", scoreType);
		parameterMap.put("category", category);
		QueryResult<ResultMap<String, Object>> result = userAdditionalScoreDao.findMapListBySQLKey(sqlKey, parameterMap,
				null);

		return result.getContent();
	}

	private String getDepartmentCodebyStaffId(String staffId) {
		User uesr = userDao.findByStaffId(staffId);
		String departmentCode = uesr.getDepartmentCode();
		return departmentCode;
	}

	/**
	 * 额外分一键审批（第三方）--单人
	 */
	public Boolean submitScore(List<UserAdditionalScore> list) throws Exception {
		UserAdditionalScore userAdditionalScore = new UserAdditionalScore();
		if (null == list || list.size() == 0) {
			throw new Exception("scoreIdList is null");
		} else {
			String staffId = userDao.findByUserId(userAdditionalScoreDao.findById(list.get(0).getId()).getUserId())
					.getStaffId();
			for (int i = 0; i < list.size(); i++) {
				userAdditionalScore = userAdditionalScoreDao.findById(list.get(i).getId());
				userAdditionalScore.setAuditScore(userAdditionalScore.gettLScore());
				userAdditionalScore.setStatus(STATUS_FINAL);
				userAdditionalScoreDao.save(userAdditionalScore);
				// 统计总分
				SumScore.sum(staffId, userAdditionalScore.getYear(), userAdditionalScore.getMonth());
			}
			return Boolean.TRUE;
		}
	}

	/**
	 * 额外分一键审批（第三方）--所有人
	 */
	public Boolean submitAllScorebyAdmin(String staffId) {
		UserAdditionalScore userAdditionalScore = new UserAdditionalScore();
		String departmentCode = userDao.findByStaffId(staffId).getDepartmentCode();
		List<String> list = userAdditionalScoreDao.findScoreIdByDepartmentCode(departmentCode);
		if (null == list || list.size() == 0) {
			return Boolean.FALSE;
		} else {
			String scoreId = "";
			for (int i = 0; i < list.size(); i++) {
				scoreId = userAdditionalScoreDao.findById(list.get(i)).getId();
				String scoreStaffId = userDao.findByUserId(userAdditionalScoreDao.findById(scoreId).getUserId())
						.getStaffId();
				userAdditionalScore = userAdditionalScoreDao.findById(scoreId);
				userAdditionalScore.setAuditScore(userAdditionalScore.gettLScore());
				userAdditionalScore.setStatus(STATUS_FINAL);
				userAdditionalScoreDao.save(userAdditionalScore);
				// 统计总分
				SumScore.sum(scoreStaffId, userAdditionalScore.getYear(), userAdditionalScore.getMonth());
			}
			return Boolean.TRUE;
		}
	}

}
